package com.sykj.cloud.gateway.filter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import com.sykj.cloud.common.core.utils.StringUtils;
import com.sykj.cloud.common.core.utils.ip.IpUtils;
import com.sykj.cloud.common.core.web.domain.AjaxResult;
import com.sykj.cloud.common.redis.service.RedisService;
import com.sykj.cloud.gateway.service.ValidateCodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.nio.CharBuffer;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.atomic.AtomicReference;

import static com.sykj.cloud.common.core.constant.Constants.USER_LOGIN_ERROR_COUNT;
import static com.sykj.cloud.common.core.constant.Constants.USER_LOGIN_ERROR_COUNT_LIMIT;

/**
 * 验证码过滤器
 *
 * @author ruoyi
 */
@Component
public class ValidateCodeFilter extends AbstractGatewayFilterFactory<Object> {

    private final static String AUTH_URL = "/auth/login";

    @Autowired
    private ValidateCodeService validateCodeService;

    @Autowired
    RedisService redisService;

    private static final String CODE = "code";

    private static final String UUID = "uuid";

    @Override
    public GatewayFilter apply(Object config) {
        return (exchange, chain) -> {
            ServerHttpRequest request = exchange.getRequest();

            // 非登录请求，不处理
            if (!StringUtils.containsIgnoreCase(request.getURI().getPath(), AUTH_URL)) {
                return chain.filter(exchange);
            }

            // 登录错误次数未超过上限，不处理
            Object cacheObject = redisService.getCacheObject(USER_LOGIN_ERROR_COUNT + "_" + IpUtils.getHostIp());
            if (cacheObject == null) {
                return chain.filter(exchange);
            }

            if (Integer.parseInt(cacheObject.toString()) <= USER_LOGIN_ERROR_COUNT_LIMIT) {
                return chain.filter(exchange);
            }
            // 若错误次数超过次数上限，则需要输入验证码，
            try {
                String rspStr = resolveBodyFromRequest(request);
                JSONObject obj = JSONObject.parseObject(rspStr);
                validateCodeService.checkCapcha(obj.getString(CODE), obj.getString(UUID));
            } catch (Exception e) {
                ServerHttpResponse response = exchange.getResponse();
                response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
                return exchange.getResponse().writeWith(
                        Mono.just(response.bufferFactory().wrap(JSON.toJSONBytes(AjaxResult.error(e.getMessage())))));
            }
            return chain.filter(exchange);
        };
    }

    private String resolveBodyFromRequest(ServerHttpRequest serverHttpRequest) {

        // 获取请求体

        // 关于Flux 和Mono 可以看下这篇blog
        // https://blog.csdn.net/java_xiaoo/article/details/108868714?utm_medium=distribute.pc_relevant.none-task-blog-title-6&spm=1001.2101.3001.4242
        Flux<DataBuffer> body = serverHttpRequest.getBody();
        AtomicReference<String> bodyRef = new AtomicReference<>();
        body.subscribe(buffer -> {
            CharBuffer charBuffer = StandardCharsets.UTF_8.decode(buffer.asByteBuffer());
            DataBufferUtils.release(buffer);
            bodyRef.set(charBuffer.toString());
        });
        return bodyRef.get();
    }
}
